<?php
Yii::import("application.extensions.paypal.*");
require_once "bootstrap.php";
session_start();
use PayPal\Api\Address;
use PayPal\Api\Amount;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\FundingInstrument;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Transaction;
use PayPal\Rest\ApiContext;
use PayPal\Api\ExecutePayment;
use PayPal\Api\PaymentExecution;

class DefaultController extends Controller
{
	public $layout='//layouts/column2';
	public function actionIndex()
	{
		Yii::log(print_r($_REQUEST,true),CLogger::LEVEL_INFO,'pay.paypal');
	}
	
	public function actionOrder(){
		$dataProvider = Order::model()->getUserOrder(Yii::app()->user->id);
		$this->render('order',array('provider'=>$dataProvider));
	}
	
	public function actionUpdateCart(){
		$cart = Utils::decodeBackboneData();
		
	}
	
	
	public function actionCart(){
		$this->render('cart');
	}
	
	
	public function actionExecutePayment(){
		global $cred;
		Yii::log(print_r($_REQUEST,true),CLogger::LEVEL_INFO,'pay.paypal');
		if(isset($_GET['success']) && $_GET['success'] == 'true') {
			$apiContext = new ApiContext($cred);
			$paymentId = $_SESSION['paymentId'];
			$payment = Payment::get($paymentId);
			
			$execution = new PaymentExecution();
			$execution->setPayer_id($_GET['PayerID']);
			try{
				//Execute the payment
				$updatetime = date('Y-m-d H:i:s');
				$payment->execute($execution, $apiContext);
				
				
				$paymentInfo = $payment->toArray();
				$paymentModel = Paypal::model()->findByAttributes(array('paymentid'=>$paymentId));
				$paymentModel->update_time = $updatetime;
				$paymentModel->intent = $paymentInfo['intent'];
				$paymentModel->email = $paymentInfo['payer']['payer_info']['email'];
				$paymentModel->payername = $paymentInfo['payer']['payer_info']['first_name'].$paymentInfo['payer']['payer_info']['last_name'];
				$paymentModel->payerid = $paymentInfo['payer']['payer_info']['payer_id'];
				$amountInfo = $paymentInfo['transactions'][0]['amount'];
				$paymentModel->amount_total = $amountInfo['total'];
				$paymentModel->amount_currency = $amountInfo['currency'];
				$paymentModel->state = 1;
				
				if($paymentModel->save()){
					$orderModel = Order::model()->findByPk($paymentModel->orderid);
					$orderModel->status = Order::FINISHED;
					$orderModel->paytime = $paymentModel->create_time;
					$orderModel->finishtime = $updatetime;
					if($orderModel->update(array('status','paytime','finishtime'))){
						echo "支付成功";
					}else{
						print_r($orderModel->getErrors());
					}
				}else{
					print_r($paymentModel->getErrors());
				}
				
				Yii::log(print_r($paymentInfo,true),CLogger::LEVEL_INFO,'pay.paypal');
			}catch(PaymentExecution $pe){
				
			}
			
		
		} else {
			echo "User cancelled payment.";
		}
	}
	
	
	public function actionProduct($id){
		global $cred;
		
		
		
		$product = Product::model()->findByPk($id);
		if(empty($product)){
			die('product is not exists');
		}		
		$payer = new Payer();
		$payer->setPayment_method("paypal");
		
		// ### Amount
		$amount = new Amount();
		$amount->setCurrency("CNY");
		$total = $product->price;
		
		$amount->setTotal($total);
		
		$transaction = new Transaction();
		
		$transaction->setAmount($amount);
		$transaction->setDescription($product->name);
		
		$redirectUrls = new RedirectUrls();
		$redirectUrls->setReturn_url($this->createAbsoluteUrl('/pay/default/ExecutePayment',array('success'=>'true')));
		$redirectUrls->setCancel_url($this->createAbsoluteUrl('/pay/default/ExecutePayment',array('success'=>'false')));
		
		$payment = new Payment();
		$payment->setIntent("sale");
		$payment->setPayer($payer);
		$payment->setRedirect_urls($redirectUrls);
		$payment->setTransactions(array($transaction));
		
		$apiContext = new ApiContext($cred, 'Request' . time());
		
		try {
			$payment->create($apiContext);
		} catch (\PPConnectionException $ex) {
			echo "Exception: " . $ex->getMessage() . PHP_EOL;
			print_r($ex->getData());
			exit(1);
		}
		
		$order = new Order();
		
		$order->createtime = date('Y-m-d H:i:s');
		$order->amount = $total;
		$order->pay_type = 'paypal';
		$order->status = Order::UN_PAY;
// 		$order->customerid = 1;
// 		$order->cartid = 1;
		
		if($order->save()){
			$_SESSION['paymentId'] = $payment->getId();
			
			$paypalModel = new Paypal();
			$paypalModel->paymentid =  $payment->getId();
			$paypalModel->payment_method = 'paypal';
			$paypalModel->create_time = date('Y-m-d H:i:s');
			$paypalModel->amount_currency = 'CNY';
			$paypalModel->amount_total = $total;
			$paypalModel->state = 0;
			$paypalModel->orderid = $order->id;
			if($paypalModel->save()){
				foreach($payment->getLinks() as $link) {
					if($link->getRel() == 'approval_url') {
						$redirectUrl = $link->getHref();
					}
				}
				
				if(isset($redirectUrl)) {
					header("Location: $redirectUrl");
					exit;
				}
			}else{
				echo "pay save failed";
				echo print_r($paypalModel->getErrors(),true);
			}
		}else{
			echo "order save failed";
			echo print_r($order->getErrors(),true);
		}
				
		
		
	}
	
	
	public function actionExe(){
		global $cred;
		$paymentId = 'PAY-2C339518RR4082344KFXG66I';
		$apiContext = new ApiContext($cred);
		
		$payment = Payment::get($paymentId);
		
		$execution = new PaymentExecution();
		
		//Execute the payment
		$payment->execute($execution, $apiContext);
		
		print_r($payment->toArray());
	}
	
	
	/**
	 * select pay method
	 * @author wanghch
	 * @email wanghch@mediav.com
	 * @date Apr 18, 2013
	 */
	public function actionSubmitOrder(){
		$customerId = Yii::app()->user->id;
		$cartMap = CartProductMap::model()->findAllByAttributes(array('customerid'=>$customerId));
		
		$order = new Order();
		$order->createtime = date('Y-m-d H:i:s');
		$order->amount = 0;
		$order->status = Order::UN_PAY;
		$order->customerid = Yii::app()->user->id;
		if($order->save()){
		}else{
		}
		
		$total = 0;
		$currency = 'USD';
		
		foreach($cartMap as $cm){
			$orderMap = new OrderProductMap();
			$orderMap->attributes = $cm->attributes;
			$orderMap->orderid = $order->id;
			$total+=$cm->total;
			$orderMap->save();
		}
		if(isset($cartMap[0])){
			$currency = $cartMap[0]->currency;
		}
		$order->isNewRecord = false;
		$order->amount = $total;
		$order->currency = $currency;
		$order->update(array('amount','currency'));
		
		CartProductMap::model()->deleteAllByAttributes(array('customerid'=>$customerId));
		
		$this->redirect(Yii::app()->createUrl("pay/order/do",array("orderid"=>$order->id)));
	}
}